package com.czy.owner.ui.workorder;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IntegerRes;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.OrderDetailsCustomAdapter;
import com.czy.owner.adapter.OrderDetailsGoodsAdapter;
import com.czy.owner.adapter.OrderDetailsServiceAdapter;
import com.czy.owner.api.OrderDetalisInfoApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.WorkOrderDetailsModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.order.OrderProcedureActivity;
import com.czy.owner.ui.store.OnLineOrderActivity2;
import com.czy.owner.utils.DecimalUtil;
import com.czy.owner.utils.IntentUtils;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.StringUtils;
import com.czy.owner.utils.TimeUtils;
import com.czy.owner.widget.MyRecyclerView;
import com.czy.owner.widget.UniversalDialog;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by hedepu on 2017-09-04
 * 工单详情
 */

public class OrderDetailsActivity3 extends BaseActivity {

    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    //订单号
    @BindView(R.id.tv_order_number)
    TextView tvOrderNumber;
    //订单状态
    @BindView(R.id.tv_order_status)
    TextView tvOrderStatus;
    //商品总价
    @BindView(R.id.tv_order_goods_money)
    TextView tvOrderGoodsMoney;
    @BindView(R.id.recyclerview_good)
    MyRecyclerView recyclerviewGood;
    //服务总价
    @BindView(R.id.tv_order_service_money)
    TextView tvOrderServiceMoney;
    @BindView(R.id.recyclerview_service)
    MyRecyclerView recyclerviewService;
    //自定义总价
    @BindView(R.id.tv_order_custom_money)
    TextView tvOrderCustomMoney;
    @BindView(R.id.recyclerview_custom)
    MyRecyclerView recyclerviewCustom;
    @BindView(R.id.linear_goods)
    LinearLayout linearGoods;
    @BindView(R.id.linear_service)
    LinearLayout linearService;
    @BindView(R.id.linear_custom)
    LinearLayout linearCustom;
    @BindView(R.id.tv_order_all_money)
    TextView tvOrderAllMoney;
    @BindView(R.id.tv_order_deposit_money)
    TextView tvOrderDepositMoney;
    @BindView(R.id.relat_order_deposit)
    RelativeLayout relatOrderDeposit;
    @BindView(R.id.tv_order_coupon_money)
    TextView tvOrderCouponMoney;
    @BindView(R.id.relat_order_coupon)
    RelativeLayout relatOrderCoupon;
    @BindView(R.id.tv_order_open_time)
    TextView tvOrderOpenTime;
    @BindView(R.id.relat_order_procedure)
    RelativeLayout relatOrderProcedure;
    @BindView(R.id.relat_order_all_money)
    RelativeLayout relatOrderAllMoney;

    //    @BindView(R.id.tv_bottom_type)
//    TextView tvBottomType;
//    @BindView(R.id.tv_order_money)
//    TextView tvOrderMoney;
    @BindView(R.id.tv_money_type)
    TextView tvMoneyType;
    @BindView(R.id.img_deposit)
    ImageView imgDeposit;


    @BindView(R.id.btn_order_paid)
    Button btnOrderPaid;
    @BindView(R.id.relat_bottom)
    RelativeLayout relatBottom;
    @BindView(R.id.img_right_money)
    ImageView imgRightMoney;
    @BindView(R.id.img_right)
    ImageView imgRight;
    @BindView(R.id.tv_store_name)
    TextView tvStoreName;
    private String orderNumber, userOrderId;
    //待处理， created ，待付定金，  waitPayDeposit   ，， 待服务  waitService 服务中inService,  支付余款 inSettlement  已付尾款hasPayed,
    // 已完成completed 已评价commented,已取消cancelled，
    public static String CREATED = "created";
    public static String WAITPAYDEPOSIT = "waitPayDeposit";
    public static String WAITSERVICE = "waitService";
    public static String INSERVICE = "inService";
    public static String INSETTLEMENT = "inSettlement";
    public static String HASPAYED = "hasPayed";
    public static String COMPLETED = "completed";
    public static String CANCELLED = "cancelled";
    public static String COMMENTED = "commented";
    public static final String ININSPECTION = "inInspection";//质检中，app显示为服务中

    private OrderDetailsGoodsAdapter orderDetailsGoodsAdapter;
    private OrderDetailsServiceAdapter orderDetailsServiceAdapter;
    private OrderDetailsCustomAdapter orderDetailsCustomAdapter;
    private WorkOrderDetailsModel workOrderDetailsModel;
    @BindView(R.id.tv_empty_content)
    TextView tvEmptyContent;
    @BindView(R.id.linear_empty)
    LinearLayout linearEmpty;
    private String toastContent = "数据加载中...";
    private int storeId = 0;
    private boolean isMessage;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_my_order_detail3;
    }

    @Override
    protected void initInjector() {
        RxBus.getDefault().register(this);
        orderNumber = getIntent().getStringExtra("orderNumber");
        userOrderId = getIntent().getStringExtra("userOrderId");
        storeId = getIntent().getIntExtra("storeId", 0);
        isMessage = getIntent().getBooleanExtra("isMessage", false);
        MyLog.e("hep", storeId + "-----------------");
//        getData();
    }

    /*接受事件*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(CommonEvent changeText) {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
          /*註銷*/
        RxBus.getDefault().unRegister(this);
    }

    @Override
    protected void initViews() {

        toolbarTitle.setText("工单详情");
        imgRight.setImageResource(R.mipmap.order_phone);
        imgRight.setVisibility(View.GONE);
        tvEmptyContent.setText(toastContent);
        getData();

    }

    @Override
    protected void updateViews() {

    }

    public void setTextData(WorkOrderDetailsModel workOrderDetailsModel) {
        tvOrderNumber.setText("工单编号：" + workOrderDetailsModel.getOrderNumber());
        storeId = Integer.parseInt(workOrderDetailsModel.getStoreId());
        tvStoreName.setText(workOrderDetailsModel.getStoreName());
        //待处理
        if (workOrderDetailsModel.getOrderStatus().equals(CREATED)) {
            tvOrderStatus.setText("待处理");
            finish();
            //待付定金
        } else if (workOrderDetailsModel.getOrderStatus().equals(WAITPAYDEPOSIT)) {
            tvOrderStatus.setText("待付款");
            finish();
            //待服务
        } else if (workOrderDetailsModel.getOrderStatus().equals(WAITSERVICE)) {
            tvOrderStatus.setText("待服务");
            finish();
            //服务中
        } else if (workOrderDetailsModel.getOrderStatus().equals(INSERVICE) || workOrderDetailsModel.getOrderStatus().equals(ININSPECTION)) {
            tvOrderStatus.setText("服务中");
            tvOrderDepositMoney.setText("¥" + DecimalUtil.formatNum(workOrderDetailsModel.getPayAmount()));
            btnOrderPaid.setVisibility(View.GONE);
            relatOrderCoupon.setVisibility(View.GONE);
            tvOrderOpenTime.setText("开单时间：" + TimeUtils.timeStamp2Date(workOrderDetailsModel.getOpenTime(), "yyyy-MM-dd HH:mm"));
            if (StringUtils.isEmpty(workOrderDetailsModel.getStoreBookingNumber()) || (workOrderDetailsModel.getDepositPayDetail() == null || Double.parseDouble(StringUtils.getString(workOrderDetailsModel.getDepositPayDetail().getPayedDepositAmount(), "0")) == 0)) {
                tvMoneyType.setText("待付金额");

            } else {
                tvMoneyType.setText("待付尾款");
                imgDeposit.setVisibility(View.VISIBLE);
            }
            relatBottom.setVisibility(View.GONE);
            //待付余款
        } else if (workOrderDetailsModel.getOrderStatus().equals(INSETTLEMENT)) {

            tvOrderDepositMoney.setText("¥" + DecimalUtil.formatNum(workOrderDetailsModel.getPayAmount()));
            btnOrderPaid.setText("付款");
            if (StringUtils.isEmpty(workOrderDetailsModel.getStoreBookingNumber()) || (workOrderDetailsModel.getDepositPayDetail() == null || Double.parseDouble(StringUtils.getString(workOrderDetailsModel.getDepositPayDetail().getPayedDepositAmount(), "0")) == 0)) {
                tvOrderStatus.setText("待付金额");
                tvMoneyType.setText("待付金额");

            } else {
                tvMoneyType.setText("待付尾款");
                tvOrderStatus.setText("待付尾款");
                imgDeposit.setVisibility(View.VISIBLE);
            }

            tvOrderOpenTime.setText("开单时间：" + TimeUtils.timeStamp2Date(workOrderDetailsModel.getOpenTime(), "yyyy-MM-dd HH:mm"));
            //完成待评价
        } else if (workOrderDetailsModel.getOrderStatus().equals(COMPLETED)) {
            tvOrderStatus.setText("待评价");
            btnOrderPaid.setText("去评价");
            tvMoneyType.setText("实付金额");


            tvOrderDepositMoney.setText("¥" + DecimalUtil.sub(workOrderDetailsModel.getTotalPrice(), getNonRealPayment()));
            tvOrderOpenTime.setText("完工时间：" + TimeUtils.timeStamp2Date(workOrderDetailsModel.getConstructionStopTime(), "yyyy-MM-dd HH:mm"));
//            relatOrderDeposit.setVisibility(View.GONE);
            btnOrderPaid.setBackgroundResource(R.drawable.selector_order_bt_detalis_deposit_apptheme);
            if (Double.parseDouble(workOrderDetailsModel.getTotalPrice()) != 0)
                imgDeposit.setVisibility(View.VISIBLE);
            // 已评价commented
        } else if (workOrderDetailsModel.getOrderStatus().equals(COMMENTED)) {
            tvOrderStatus.setText("工单完成");
            btnOrderPaid.setText("查看评价");
            tvMoneyType.setText("实付金额");
//            relatOrderDeposit.setVisibility(View.GONE);
            btnOrderPaid.setBackgroundResource(R.drawable.selector_order_bt_detalis_deposit_apptheme);
//            DecimalUtil.sub(DecimalUtil.sub(model.getTotalPrice(), model.getDiscountAmountMoney()), model.getDiscountAmount())
            tvOrderDepositMoney.setText("¥" + DecimalUtil.sub(workOrderDetailsModel.getTotalPrice(), getNonRealPayment()));
            tvOrderOpenTime.setText("完工时间：" + TimeUtils.timeStamp2Date(workOrderDetailsModel.getConstructionStopTime(), "yyyy-MM-dd HH:mm"));
            if (Double.parseDouble(workOrderDetailsModel.getTotalPrice()) != 0)
                imgDeposit.setVisibility(View.VISIBLE);
        } else if (workOrderDetailsModel.getOrderStatus().equals(CANCELLED)) {
            tvOrderStatus.setText("工单取消");
            relatBottom.setVisibility(View.GONE);
            relatOrderCoupon.setVisibility(View.GONE);
            tvMoneyType.setText("退还订金");
//            relatOrderDeposit.setVisibility(View.GONE);

//            if (!StringUtils.isEmpty(workOrderDetailsModel.getStoreBookingNumber()) && Double.parseDouble(workOrderDetailsModel.getTotalPrice()) != 0) {
//
//            }
            tvOrderDepositMoney.setText(workOrderDetailsModel.getDepositAmount());
            if (Double.parseDouble(StringUtils.getString(workOrderDetailsModel.getDepositAmount(), "0")) > 0) {
                imgDeposit.setVisibility(View.VISIBLE);
            }
            tvOrderOpenTime.setText("取消时间：" + TimeUtils.timeStamp2Date(workOrderDetailsModel.getCancelTime(), "yyyy-MM-dd HH:mm"));

        } else {
            relatBottom.setVisibility(View.GONE);

        }
        //商品总价
//        tvOrderGoodsMoney;
//        recyclerviewGood;
        if (workOrderDetailsModel.getGoodsItemList() != null && workOrderDetailsModel.getGoodsItemList().size() > 0) {
            recyclerviewGood.setLayoutManager(new LinearLayoutManager(this));
            orderDetailsGoodsAdapter = new OrderDetailsGoodsAdapter(this, workOrderDetailsModel.getGoodsItemList());
            recyclerviewGood.setAdapter(orderDetailsGoodsAdapter);
            recyclerviewGood.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, R.drawable.shape_gray_divider_decoration));
            tvOrderGoodsMoney.setText("小计：¥" + orderDetailsGoodsAdapter.getAllMoney());
            if (workOrderDetailsModel.getOrderStatus().equals(INSERVICE) || workOrderDetailsModel.getOrderStatus().equals(ININSPECTION)) {
                orderDetailsGoodsAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position, Object o, View view) {
                        showDialog(orderDetailsGoodsAdapter.getList().get(position).getOrderItemEmps());
                    }
                });
            }
        } else {
            linearGoods.setVisibility(View.GONE);

        }
//        LinearLayout linearGoods;
//        LinearLayout linearService;
//        LinearLayout linearCustom;
//        //服务总价
//        tvOrderServiceMoney;
//        recyclerviewService;
        if (workOrderDetailsModel.getServiceItemsList() != null && workOrderDetailsModel.getServiceItemsList().size() > 0) {
            recyclerviewService.setLayoutManager(new LinearLayoutManager(this));
            orderDetailsServiceAdapter = new OrderDetailsServiceAdapter(this, workOrderDetailsModel.getServiceItemsList());
            recyclerviewService.setAdapter(orderDetailsServiceAdapter);
            recyclerviewService.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, R.drawable.shape_gray_divider_decoration));
            tvOrderServiceMoney.setText("小计：¥" + orderDetailsServiceAdapter.getAllMoney());
            if (workOrderDetailsModel.getOrderStatus().equals(INSERVICE) || workOrderDetailsModel.getOrderStatus().equals(ININSPECTION)) {
                orderDetailsServiceAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position, Object o, View view) {
                        showDialog(orderDetailsServiceAdapter.getList().get(position).getOrderItemEmps());
                    }
                });
            }
        } else {
            linearService.setVisibility(View.GONE);
        }
//        //自定义总价
//        tvOrderCustomMoney;
//        recyclerviewCustom;
        if (workOrderDetailsModel.getCustomItemList() != null && workOrderDetailsModel.getCustomItemList().size() > 0) {
            recyclerviewCustom.setLayoutManager(new LinearLayoutManager(this));
            orderDetailsCustomAdapter = new OrderDetailsCustomAdapter(this, workOrderDetailsModel.getCustomItemList());
            recyclerviewCustom.setAdapter(orderDetailsCustomAdapter);
            recyclerviewCustom.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, R.drawable.shape_gray_divider_decoration));
            tvOrderCustomMoney.setText("小计：¥" + orderDetailsCustomAdapter.getAllMoney());
            if (workOrderDetailsModel.getOrderStatus().equals(INSERVICE) || workOrderDetailsModel.getOrderStatus().equals(ININSPECTION)) {

                orderDetailsCustomAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position, Object o, View view) {
                        showDialog(orderDetailsCustomAdapter.getList().get(position).getOrderItemEmps());
                    }
                });
            }
        } else {
            linearCustom.setVisibility(View.GONE);
        }
        tvOrderAllMoney.setText("¥" + DecimalUtil.formatNum(workOrderDetailsModel.getTotalPrice()));

//        tvOrderDepositMoney.setText("¥" + DecimalUtil.formatNum(workOrderDetailsModel.getActualDepositAmount()));
//        tvOrderMoney.setText("¥" + DecimalUtil.add(workOrderDetailsModel.getDepositPayDetail(),workOrderDetailsModel.getActualAmount())workOrderDetailsModel.getTotalPrice());


    }

    public String getNonRealPayment() {
        String nonRealPayment = "";
        if (workOrderDetailsModel.getDepositPayDetail() != null) {
            nonRealPayment = DecimalUtil.add(nonRealPayment, workOrderDetailsModel.getDepositPayDetail().getHang());

        }
        if (workOrderDetailsModel.getBalancePayDetail() != null) {
            nonRealPayment = DecimalUtil.add(nonRealPayment, workOrderDetailsModel.getBalancePayDetail().getHang());
            nonRealPayment = DecimalUtil.add(nonRealPayment, workOrderDetailsModel.getBalancePayDetail().getCouponsPay());
            nonRealPayment = DecimalUtil.add(nonRealPayment, workOrderDetailsModel.getBalancePayDetail().getPersonHang());

        }
        nonRealPayment = DecimalUtil.add(nonRealPayment, workOrderDetailsModel.getDiscountAmountMoney());
        return nonRealPayment;
    }

    public void showDialog(String string) {
        String content;
        if (StringUtils.isEmpty(string)) {
            content = "我们店最厉害的技师正在用最娴熟的手法，最快的速度为您服务～";
        } else {
            content = string + "正在用最专业的操作，最快的速度为您服务～";
        }


        //待服务
        new UniversalDialog(OrderDetailsActivity3.this).builder()
                .setCancelable(false)
                .setMsg(content)
                .setPositiveButton("好的", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                }).show();
    }

    //获取订单
    private void getData() {
        OrderDetalisInfoApi orderDetalisInfoApi = new OrderDetalisInfoApi(new HttpOnNextListener<WorkOrderDetailsModel>() {
            @Override
            public void onNext(WorkOrderDetailsModel o) {
                workOrderDetailsModel = o;
                imgRight.setVisibility(View.VISIBLE);
                setTextData(o);
                linearEmpty.setVisibility(View.GONE);


            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
                tvEmptyContent.setText("加载失败，点击重新加载...");
                PhoneUtils.ShowToastMessage(OrderDetailsActivity3.this, "获取订单信息异常");
            }
        }, this);
        ;
        orderDetalisInfoApi.setSession(UserHelper.getInstance().getSessionInfoModel(this).getSession());
        orderDetalisInfoApi.setOrderNumber(orderNumber);
        HttpManager.getInstance().doHttpDeal(orderDetalisInfoApi);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.relat_order_deposit, R.id.relat_order_procedure, R.id.btn_order_paid, R.id.relat_order_all_money, R.id.linear_empty, R.id.linear_right_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //拨打电话
            case R.id.linear_right_img:
                IntentUtils.onClickCallPhone(OrderDetailsActivity3.this, workOrderDetailsModel.getServiceNumber());
                break;
            //支付详情
            case R.id.relat_order_deposit:
                if (imgDeposit.getVisibility() == View.VISIBLE) {
                    startActivity(new Intent(OrderDetailsActivity3.this, PaymentDetailsActivity.class).putExtra("orderDetails", workOrderDetailsModel).putExtra("type", "1")
                            .putExtra("titleText", tvMoneyType.getText().toString()).putExtra("titleMoney", tvOrderDepositMoney.getText().toString()));
                }
                break;
            //工单流程
            case R.id.relat_order_procedure:
                startActivity(new Intent(OrderDetailsActivity3.this, OrderProcedureActivity.class).putExtra("orderDetails", workOrderDetailsModel));
                break;
            case R.id.relat_order_all_money:
//                //待评价
//                if (workOrderDetailsModel.getOrderStatus().equals(COMPLETED) && imgRightMoney.getVisibility() == View.VISIBLE) {
//                    startActivity(new Intent(OrderDetailsActivity3.this, PaymentDetailsActivity.class).putExtra("orderDetails", workOrderDetailsModel));
//                    // 已评价commented
//                } else if (workOrderDetailsModel.getOrderStatus().equals(COMMENTED) && imgRightMoney.getVisibility() == View.VISIBLE) {
//                    startActivity(new Intent(OrderDetailsActivity3.this, PaymentDetailsActivity.class).putExtra("orderDetails", workOrderDetailsModel));
//                    //工单取消 且是预约
//                } else if (workOrderDetailsModel.getOrderStatus().equals(CANCELLED) && !StringUtils.isEmpty(workOrderDetailsModel.getStoreBookingNumber()) && imgRightMoney.getVisibility() == View.VISIBLE) {
//                    startActivity(new Intent(OrderDetailsActivity3.this, PaymentDetailsActivity.class).putExtra("orderDetails", workOrderDetailsModel));
//
//                }
                break;
            case R.id.btn_order_paid:
                //服务中
                if (workOrderDetailsModel.getOrderStatus().equals(INSERVICE)) {

                    //待付余款
                } else if (workOrderDetailsModel.getOrderStatus().equals(INSETTLEMENT)) {
                    Intent ti = new Intent(this, PaidEndOfPaymentActivity2.class);
                    ti.putExtra("orderNumber", workOrderDetailsModel.getOrderNumber());
                    ti.putExtra("storeId", storeId);
                    ti.putExtra("userOrderId", userOrderId);
                    ti.putExtra("isbespoke", !StringUtils.isEmpty(StringUtils.getString(workOrderDetailsModel.getStoreBookingNumber())));
                    ti.putExtra("isMessage", isMessage);
                    startActivity(ti);
                    //待评价
                } else if (workOrderDetailsModel.getOrderStatus().equals(COMPLETED)) {
                    Intent ti = new Intent(this, EvaluateActivity2.class);
                    ti.putExtra("orderNumber", workOrderDetailsModel.getOrderNumber());
                    ti.putExtra("storeId", storeId);
                    ti.putExtra("isMessage", isMessage);
                    startActivity(ti);
                    // 已评价commented
                } else if (workOrderDetailsModel.getOrderStatus().equals(COMMENTED)) {
                    Intent ti = new Intent(this, SeeEvaluateActivity2.class);
                    ti.putExtra("orderNumber", workOrderDetailsModel.getOrderNumber());
                    ti.putExtra("storeId", storeId);
                    startActivity(ti);

                }
                break;
            case R.id.linear_empty:
                if (tvEmptyContent.getText().toString().equals(toastContent))
                    return;
                tvEmptyContent.setText(toastContent);
                getData();
                break;

        }
    }
}
